<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          v-has-permission="['sms:activity:add']"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-has-permission="['sms:activity:delete']"
          type="danger"
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange" border
              :header-cell-style="{background:'#EAE9E9FF'}"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="活动标题" align="center" prop="title"/>
      <el-table-column label="活动大图" align="center" prop="icon">
        <template slot-scope="scope">
          <el-image :src="scope.row.icon" style="width: 60px; height: 60px">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"/>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="活动类型" align="center" prop="type">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 1">满金额送</span>
          <span v-if="scope.row.type == 2">满数量送</span>
          <!--          <span v-if="scope.row.type == 3">充值送钱</span>-->
          <span v-if="scope.row.type == 4">充值送礼品</span>
        </template>
      </el-table-column>
      <el-table-column label="会员等级" align="center" prop="level.name"/>
      <el-table-column label="达标金额" align="center" prop="discount"/>
      <el-table-column label="商品达标数量" align="center" prop="goodsCount"/>
      <!--      <el-table-column label="赠送金额" align="center" prop="money" />-->
      <el-table-column label="开始时间" align="center" prop="startTime" width="180"/>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180"/>
      <el-table-column label="状态" align="center" width="160">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            loading
            active-text="开启"
            inactive-text="关闭"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-has-permission="['sms:activity:update']"
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <!--          <el-button-->
          <!--            v-has-permission="['sms:activity:delete']"-->
          <!--            size="mini"-->
          <!--            type="danger"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--          >删除-->
          <!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="pagination.total > 0"
      :total="pagination.total"
      :page.sync="pagination.pageNum"
      :limit.sync="pagination.pageSize"
      @pagination="handleQuery"
    />
    <!-- 添加或修改活动对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="60%" append-to-body>
      <el-dialog
        :visible.sync="sendGoodsVisible"
        width="60%"
        title="选择商品"
        append-to-body
      >
        <el-form ref="queryGoodsForm" :inline="true" :model="queryGoodsForm" label-width="100px">
          <el-form-item label="商品名称">
            <el-input
              v-model="queryGoodsForm.goodsName"
              clearable
              placeholder="请输入商品名称"
              size="small"
              @keyup.enter.native="toQueryGoodsList"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="mini" type="success" @click="toQueryGoodsList"
                       v-has-permission="['sms:activity:productList']"
            >搜索
            </el-button>
            <el-button icon="el-icon-plus" size="mini" type="primary" @click="sendGoodsVisible = false">提交</el-button>
          </el-form-item>
        </el-form>

        <el-table ref="goodsListTable" :data="goodsList" style="width: 100%"
                  @selection-change="handleGoodsSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column prop="id" label="商品货号">
            <template slot-scope="scope">
              <span>No.{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" width="180"/>
          <el-table-column prop="image" label="商品图片" width="180">
            <template slot-scope="scope">
              <el-image :src="scope.row.image" style="width: 60px; height: 60px">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"/>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="商品库存" width="180"/>
          <el-table-column label="赠送数量">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.count"
                :min="1"
                :max="scope.row.stock"
              />
              <!--              <span v-show="!scope.row.show">{{ scope.row.count }}</span>-->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="paginationGoodsInfo.total > 0"
          :total="paginationGoodsInfo.total"
          :page.sync="paginationGoodsInfo.pageNum"
          :limit.sync="paginationGoodsInfo.pageSize"
          @pagination="toQueryGoodsList"
        />
      </el-dialog>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题"/>
        </el-form-item>
        <el-form-item label="活动大图" prop="icon">
          <single-upload v-model="form.icon"/>
        </el-form-item>
        <el-form-item label="会员等级" prop="memberLevel">
          <el-select v-model="form.memberLevel" clearable placeholder="请选择">
            <el-option
              v-for="item in memberLevelList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <template v-if="form.type != 2">
          <el-form-item label="达标金额" prop="discount">
            <el-input-number v-model="form.discount" :min="0" :precision="2"/>
          </el-form-item>
        </template>
        <template v-if="form.type == 2">
          <el-form-item label="商品达标数量" prop="goodsCount">
            <el-input-number v-model="form.goodsCount" :min="0"/>
          </el-form-item>
        </template>
        <!--        <template v-if="form.type != 4">-->
        <!--          <el-form-item label="赠送金额" prop="money">-->
        <!--            <el-input-number v-model="form.money" :min="0" :precision="2" />-->
        <!--          </el-form-item>-->
        <!--        </template>-->
        <template v-if="form.type != 3">
          <el-form-item label="赠送商品" prop="goodsIds">
            <el-button type="primary" size="mini" @click="sendGoods">选择商品</el-button>
            <el-table v-show="selectGoodsList.length > 0" :data="selectGoodsList" style="width: 100%">
              <el-table-column prop="id" label="商品货号">
                <template slot-scope="scope">
                  <span>No.{{ scope.row.id }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称"/>
              <el-table-column prop="image" label="商品图片">
                <template slot-scope="scope">
                  <el-image :src="scope.row.image" style="width: 60px; height: 60px">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"/>
                    </div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="商品库存" width="180"/>
              <el-table-column prop="count" label="赠送数量"/>
            </el-table>
          </el-form-item>
        </template>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="chooseDateTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="right"
            clearable
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-has-permission="['sms:activity:update','sms:activity:add']">确
          定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { downloadFile } from '@/utils'

import {
  getActivity,
  addActivity,
  delActivity,
  exportActivity,
  listActivity,
  updateActivity,
  updateActivityStatus
} from '@/api/sms/activity'
import SingleUpload from '@/components/Upload/SingleUpload'
import { listMember_level } from '@/api/ums/member_level'
import { listGoodsInfo } from '@/api/pms/yxStoreProduct'
import checkPermission from '@/utils/permission'

export default {
  name: 'Activity',
  components: {
    SingleUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      goodsIds: [],
      chooseDateTime: [],
      selectGoodsList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 非单个禁用
      goodsSingle: true,
      // 非多个禁用
      goodsMultiple: true,
      // 显示搜索条件
      showSearch: true,
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      paginationGoodsInfo: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 活动表格数据
      activityList: [],
      goodsList: [],
      // 弹出层
      sendGoodsVisible: false,
      dialog: {
        title: undefined,
        visible: false,
        type: undefined // type 操作类型：1-新增 2-修改
      },
      // 查询参数
      queryParams: {
        title: null,
        icon: null,
        status: null,
        discount: null,
        goodsIds: null,
        type: null,
        money: null,
        memberLevel: null,
        startTime: null,
        endTime: null,
        goodsCount: null
      },
      queryGoodsForm: {},
      memberLevelList: [],
      typeList: [
        { label: '满金额送', value: 1 },
        { label: '满数量送', value: 2 },
        // { label: '充值送钱', value: 3 },
        { label: '充值送礼品', value: 4 }
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'change' }
        ],
        type: [
          { required: true, message: '活动类型不能为空', trigger: 'change' }
        ],
        memberLevel: [
          { required: true, message: '会员等级不能为空', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '开始时间不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '结束时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getMemberLevelList()
  },
  methods: {
    checkPermission,
    /** 查询活动列表 */
    getList() {
      this.loading = true
      Object.keys(this.queryParams).forEach(key => {
        this.queryParams[key] == '' ? this.queryParams[key] = null : false
      })
      this.queryParams.pageNum = this.pagination.pageNum
      this.queryParams.pageSize = this.pagination.pageSize
      listActivity(this.queryParams).then(response => {
        const { data } = response
        this.activityList = data.list
        this.pagination.total = data.totalCount
        this.loading = false
      }).catch(error => {
        this.loading = false
      })
    },
    toQueryGoodsList() {
      Object.keys(this.queryGoodsForm).forEach(key => {
        this.queryGoodsForm[key] == '' ? this.queryParams[key] = null : false
      })
      this.queryGoodsForm.pageNum = this.paginationGoodsInfo.pageNum
      this.queryGoodsForm.pageSize = this.paginationGoodsInfo.pageSize
      listGoodsInfo(this.queryGoodsForm).then(res => {
        const { data } = res
        const list = data.list
        list.forEach(goods => {
          // goods['show'] = false
          goods['count'] = 1
        })
        this.goodsList = list
        this.paginationGoodsInfo.total = data.totalCount
      })
    },
    // 取消按钮
    cancel() {
      this.reset()
      this.closeDialog()
    },
    handleReset() {
      this.pagination = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.queryParams = {
        title: null,
        icon: null,
        status: null,
        discount: null,
        goodsIds: null,
        type: null,
        money: null,
        memberLevel: null,
        startTime: null,
        endTime: null,
        goodsCount: null
      }
      this.handleQuery()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        icon: null,
        status: 0,
        discount: null,
        goodsIds: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        remark: null,
        isDelete: null,
        type: null,
        money: null,
        memberLevel: null,
        startTime: null,
        endTime: null,
        goodsCount: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    resetForm(val) {
      if (this.$refs[val]) {
        this.$refs[val].resetFields()
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleGoodsSelectionChange(selection) {
      this.goodsIds = selection.map(item => item.id)
      this.selectGoodsList = selection.map(item => {
        return {
          id: item.id, productName: item.productName, image: item.image, stock: item.stock, count: item.count
        }
      })
      // this.selectGoodsList = selection
      this.goodsSingle = selection.length !== 1
      this.goodsMultiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.chooseDateTime = []
      this.selectGoodsList = []
      this.toQueryGoodsList()
      this.dialog = {
        title: '添加活动',
        visible: true,
        type: 'add'
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.toQueryGoodsList()
      this.dialog = {
        title: '修改活动',
        visible: true,
        type: 'edit'
      }
      const id = row.id || this.ids
      getActivity(id).then(response => {
        this.form = response.data
        this.chooseDateTime = [this.form.startTime, this.form.endTime]
        if (this.form.goodsInfoList) {
          this.selectGoodsList = this.form.goodsInfoList
        }
        // this.open = true;
        // this.title = "修改活动";
      })
    },
    handleStatusChange(val) {
      updateActivityStatus({ id: val.id, status: val.status })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.startTime = this.chooseDateTime[0]
          this.form.endTime = this.chooseDateTime[1]
          this.form.activityGoodsList = []
          this.selectGoodsList.forEach(item => {
            const activityGoods = {
              goodsId: item.id,
              goodsCount: item.count
            }
            this.form.activityGoodsList.push(activityGoods)
          })
          if (this.dialog.type === 'edit') {
            updateActivity(this.form).then(response => {
              this.$message.success('修改成功')
              this.closeDialog()
              this.getList()
            })
          } else {
            addActivity(this.form).then(response => {
              this.$message.success('新增成功')
              this.closeDialog()
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids
      this.$confirm('是否确认删除活动编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delActivity(ids)
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      delete queryParams.pageNum
      delete queryParams.pageSize
      this.$confirm('是否确认导出所有活动数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportActivity(queryParams)
      }).then(response => {
        downloadFile(response.data, 'client', 'xls')
      })
    },
    getMemberLevelList() {
      listMember_level({ status: 1, queryMode: 'list' }).then(res => {
        this.memberLevelList = res.data
      })
    },
    closeDialog() {
      this.dialog = {
        title: undefined,
        visible: false,
        type: undefined
      }
    },
    sendGoods() {
      this.sendGoodsVisible = true
      this.toggleSelection(this.goodsList)
    },
    toggleSelection(rows) {
      const _this = this
      rows.forEach(row => {
        if (_this.form.goodsInfoList) {
          _this.form.goodsInfoList.forEach(item => {
            if (item.id == row.id) {
              _this.$refs.goodsListTable.toggleRowSelection(row, true)
            }
          })
        }
      })
    }
  }
}
</script>
